#include "Common.h"
#include "ListenThread.h"
#include "HelpThread.h"
#include "WorkThread.h"
#include "ConnPool.h"
#include "SocketPool.h"
#include "ConfManager.h"

void SetSafeStopFlag(int32 sig)
{
    if(SAFE_STOP_FLAG == false)
    {
        WriteLog(NOTICE, "%s receive stop signal, start to stop......", APP_NAME.c_str());
        SAFE_STOP_FLAG = true;
    }
}

int32 main(int32 argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGUSR1, SetSafeStopFlag);
    signal(SIGINT, SetSafeStopFlag);
    if(argc != 2)
    {
        WriteLog(NOTICE, "Usage: ./bin/%s [conf] or ./bin/control [start|stop|restart|healthcheck]", APP_NAME.c_str());
        return -1;
    }

    CONF_PATH = std::string(argv[1]);

    WriteLog(NOTICE, "%s is starting......", APP_NAME.c_str());

    if(ConfManager::Instance()->GetIsDispatcher() > 0)
    {
        SocketPool::Instance()->Start();
    }

    Thread *pListenThread = new ListenThread();
    Thread *pHelpThread   = new HelpThread();
    std::vector<Thread*> workThreads;
    for(int32 i=0; i<ConfManager::Instance()->GetWorkThreadCnt(); i++)
    {
        workThreads.push_back(new WorkThread());
    }

    pListenThread->Run();
    usleep(500);
    pHelpThread->Run();
    for(int32 i=0; i<ConfManager::Instance()->GetWorkThreadCnt(); i++)
    {
        workThreads[i]->Run(i);
    }

    pListenThread->Join();
    pHelpThread->Join();
    for(int32 i=0; i<ConfManager::Instance()->GetWorkThreadCnt(); i++)
    {
        workThreads[i]->Join();
    }

    if(ConfManager::Instance()->GetIsDispatcher() > 0)
    {
        SocketPool::Instance()->Stop();
    }

    WriteLog(NOTICE, "%s exit successfully.", APP_NAME.c_str());

    return 0;
}
